//
//  DiseaseTableViewController.m
//  QuickCure
//
//  Created by 王震 on 16/9/13.
//  Copyright © 2016年 haoge. All rights reserved.
//

#import "DiseaseTableViewController.h"
#import "DiseaseModel.h"
#import "NSString+pinyin.h"

/** 疾病选择疾病细分列表接口 */
#define kSearchCI3Url @"http://iosapi.itcast.cn/searchCI3List.json.php"

/** 根据疾病得到医生数量接口 */
#define kMatchedDoctorCountUrl @"http://iosapi.itcast.cn/matchedDoctorCount.json.php"

/** 选择并发症列表接口 */
#define kComplicationListUrl @"http://iosapi.itcast.cn/complicationList.json.php"

//肿瘤接口参数
#define kZhongLiu (@{@"page":@1,@"page_size":@5,@"ci1_id":@1,@"keyword":@""})

@interface DiseaseTableViewController ()

@property(nonatomic,strong) NSMutableArray<UIButton *> *btnArr;
@property(nonatomic,strong) NSArray *allListArr;

@end

static NSString *reuseID = @"cc";

@implementation DiseaseTableViewController{
    
    NSArray *_listArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self loadingView];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:reuseID];
    
    [self reloadData];

    [self setNavigationItems];
}

#pragma mark - 网络缓冲提示框
-(void)loadingView{
    
    if (self.currentSelectView.tag == 11 || self.currentSelectView.tag == 22) {
        
        [SVProgressHUD setInfoImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"angle-mask.png" ofType:nil]]];
        [SVProgressHUD show];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [SVProgressHUD dismiss];
}

#pragma mark - 设置当行控制器上的items
-(void)setNavigationItems{
    
    if (self.currentSelectView.tag == 11) {
        
        UITextField *titleTF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
        titleTF.placeholder = @"请输入关键字";
        [titleTF setBackgroundColor:[UIColor whiteColor]];
        [titleTF.layer setCornerRadius:5];
        [titleTF setClipsToBounds:YES];
        
        //监控输入框内容的变化
        [titleTF addTarget:self action:@selector(searchCell:) forControlEvents:UIControlEventEditingChanged];
        
        
        //添加输入框左边的占位View
        UIView *placeV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 30)];
        [placeV setBackgroundColor:[UIColor whiteColor]];
        [titleTF setLeftView:placeV];
        [titleTF setLeftViewMode:UITextFieldViewModeAlways];
        
        self.navigationItem.titleView = titleTF;
        
        
        
        
    }else if (self.currentSelectView.tag == 22){
        
        self.navigationItem.title = @"并发症";
        
        //订阅确定按钮
        UIBarButtonItem *sureBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(sureButtonClick)];
        [sureBtn setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem = sureBtn;
        
        
    }else if(self.currentSelectView.tag == 33){
        
        self.title = @"治疗方式";
    }
}

#pragma mark - 输入框变化监控,实现模糊查询
-(void)searchCell:(UITextField *)sender{
    

    if (sender.text.length == 0) {
        self.listArray = self.allListArr;
        return;
    }
    
    NSMutableArray *newArr = [NSMutableArray array];
    [self.allListArr enumerateObjectsUsingBlock:^(DiseaseModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSString *cellStr = obj.ci3_name;
        
        NSString *pinYin = [cellStr transformToPinyin];
        NSString *py = [cellStr transformToPinyinFirstLetter];
        

        if ([pinYin containsString:sender.text] || [pinYin containsString:[sender.text lowercaseString]] || [py containsString:sender.text] || [py containsString:[sender.text lowercaseString]]) {
            
            [newArr addObject:obj];
            
        }

    }];
    
    self.listArray = [newArr copy];

}

#pragma mark - 加载网络数据
-(void)reloadData{
    
    NSString *url = [self checkURLByView:self.currentSelectView];
    NSDictionary *dict = [self checkparmasByView:self.currentSelectView];
    
    DiseaseModel *model = [[DiseaseModel alloc] init];
    
    [model getDataWithURL:url parmas:dict successBlock:^(NSArray *arr) {
        
        
        if (self.currentSelectView.tag == 22) {
            
            NSMutableArray *mArr = [NSMutableArray array];
            for (int i = 0; i < 3; i ++) {
                
                [arr enumerateObjectsUsingBlock:^(DiseaseModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    NSString *name = [obj valueForKey:@"complication_name"];
                    name = [NSString stringWithFormat:@"%@%d型",name,i + 1];
                    
                    DiseaseModel *newModel = [[DiseaseModel alloc] init];
                    [newModel setValue:name forKey:@"complication_name"];
                    [mArr addObject:newModel];
                }];
            }
            arr = [mArr copy];
        }
        
        self.allListArr = arr;
        self.listArray = self.allListArr;
        
    }];
    
}

-(NSString *)checkURLByView:(UIView *)view{

    if (view.tag == 11) {
        return kSearchCI3Url;
    }else if (view.tag == 22){
        return kComplicationListUrl;
    }
    return @"";
}
-(NSDictionary *)checkparmasByView:(UIView *)view{
    if (view.tag == 11) {
        return @{@"page":@1,@"page_size":@15,@"ci1_id":@(self.currentIndex + 1),@"keyword":@""};
    }else if (view.tag == 22){
        return @{@"page":@1,@"page_size":@15,@"ci2_id":@3};
    }
    return NULL;
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID forIndexPath:indexPath];
    DiseaseModel *model = self.listArray[indexPath.row];
    
    
    NSString *name;
    
    if (self.currentSelectView.tag == 11) {
        
        name = [model valueForKey:@"ci3_name"];
        
    }else if (self.currentSelectView.tag == 22) {
        name = [model valueForKey:@"complication_name"];
        
        UIButton *btn = [[UIButton alloc] init];
        [btn setBackgroundImage:[UIImage imageNamed:@"link_button_01"] forState:UIControlStateNormal];
        [btn setTitle:@"订阅" forState:UIControlStateNormal];
        [btn setTitle:@"已订阅" forState:UIControlStateSelected];
        
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:12]];

        btn.selected = model.isCheckBtnSelected;
        
        btn.frame = CGRectMake(0, 0, 50, 30);
        
        cell.accessoryType = UITableViewCellAccessoryDetailButton;
        cell.accessoryView = btn;
        btn.tag = indexPath.row;
        
        [btn addTarget:self action:@selector(checkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        

        
    }else if (self.currentSelectView.tag == 33){
        
        name = self.listArray[indexPath.row];
    }
    
    cell.textLabel.text = name;
    //    cell.accessoryView
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString *cellStr;
    if (self.currentSelectView.tag == 22) {
        return;
    }
    
    if (self.currentSelectView.tag == 11) {
        
        DiseaseModel *model = self.listArray[indexPath.row];
        
        cellStr = [model valueForKey:@"ci3_name"];
       
    }else if (self.currentSelectView.tag == 33){
        
       cellStr = self.listArray[indexPath.row];
    }
    
    if (self.checkBlock) {
        self.checkBlock(cellStr);
    }
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 并发症页面 cell中订阅按钮点击事件
-(void)checkBtnClick:(UIButton *)sender{
    
    sender.selected = !sender.isSelected;
    [self.btnArr addObject:sender];
    
    DiseaseModel *model = self.listArray[sender.tag];
    
    model.isCheckBtnSelected = sender.isSelected;
    
    if (sender.selected) {
        [sender.titleLabel setFont:[UIFont systemFontOfSize:15]];
    }else{
        [sender.titleLabel setFont:[UIFont systemFontOfSize:12]];
    }

}

//并发症页面,确定按钮点击事件
-(void)sureButtonClick{
    
   __block NSMutableString *str = [NSMutableString string];
    [self.btnArr enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (obj.selected == YES) {
            
            DiseaseModel *model = self.listArray[obj.tag];
            NSString *cellStr = [model valueForKey:@"complication_name"];
            //壁立千仞,无欲则刚
            [str appendFormat:@"%@,",cellStr];
            
        }
    }];
    
    [self.navigationController popViewControllerAnimated:YES];
    
    //删除最后一个逗号
    [str deleteCharactersInRange:NSMakeRange(str.length - 1, 1)];

    if (self.checkBlock) {
        self.checkBlock([str copy]);
    }
    
}

-(void)setListArray:(NSArray *)listArray{
    _listArray = listArray;
    
    //关闭网络缓冲提示框
    [SVProgressHUD dismiss];
    [self.tableView reloadData];
}

-(NSArray *)allListArr{
    if (nil == _allListArr) {
        _allListArr = [NSArray array];
    }
    return _allListArr;
}

-(NSArray *)listArray{
    if (_listArray == nil) {
        _listArray = [NSArray array];
        if (self.currentSelectView.tag == 33) {
            
            _listArray = @[@"手术",@"药物治疗",@"保守治疗"];

        }
    }
    return _listArray;
}

-(NSMutableArray<UIButton *> *)btnArr{
    if (nil == _btnArr) {
        _btnArr = [NSMutableArray array];
    }
    return _btnArr;
}

@end
